package cn.kgc.junketing.provider.exception;

import cn.kgc.junketing.provider.vo.ResponseBean;
import cn.kgc.junketing.provider.vo.ResponseBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResponseBean handleException(Throwable throwable) {
        throwable.printStackTrace();
        if (throwable instanceof BindException) {
            BindException bindException = (BindException) throwable;
            ResponseBean responseBean = ResponseBean.error(ResponseBeanEnum.BINDERROR);
            responseBean.setMessage(bindException.getAllErrors().get(0).getDefaultMessage());
            return responseBean;
        }
        if (throwable instanceof GlobalException) {
            GlobalException globalException = (GlobalException)throwable;
            return  ResponseBean.error(globalException.getResponseBeanEnum());
        }
        return ResponseBean.error(ResponseBeanEnum.ERROR);
    }
}
